package models

import (
	"errors"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var DB *gorm.DB = nil
var err error
var isInit bool = false

// GetDB return DB
func GetDB(loginStr string) (*gorm.DB, error) {
	if isInit {
		return DB, nil
	} else {
		DB, err = initGormDB(loginStr)
		isInit = err == nil
	}
	return DB, err
}

func GetDBOnly() (*gorm.DB, error) {
	if !isInit {
		return nil, errors.New("db not init")
	}
	return DB, nil
}

// InitGormDB init DB
func initGormDB(loginStr string) (*gorm.DB, error) {

	db, err := gorm.Open(mysql.Open(loginStr), &gorm.Config{})
	if err != nil {
		//panic(err)
		return nil, err
	}

	// 强制单数形式命名
	//db.SingularTable(true) //表生成结尾不带s

	// The beginning to: Set sql.DB:
	sqldb, err := db.DB()
	if err != nil {
		return nil, err
	}
	sqldb.SetConnMaxLifetime(1 * time.Second) //设置连接超时时间
	sqldb.SetMaxIdleConns(20)                 //最大打开的连接数
	sqldb.SetMaxOpenConns(2000)               //设置最大闲置个数
	// The ending to: Set sql.DB.

	// The beginning to: Auto Migrate Table:
	//db.AutoMigrate(&Table1{})
	db.AutoMigrate(&Students{})
	db.AutoMigrate(&Discussions{})
	db.AutoMigrate(&Students{})
	db.AutoMigrate(&Queries{})
	db.AutoMigrate(&Jobs{})
	// The ending to: Auto Migrate Table.

	return db, nil
}

func AddInitData(db *gorm.DB) error {
	if db == nil {
		return errors.New("DBHandler: You Input a nil DB!")
	}

	// The beginning to: Add Init Data:
	// Add Companies:
	db.Create(&CompaniesInitData)

	// Add Jobs:
	db.Create(&JobsInitData)
	// Add Students:
	// Add Discussions:
	// Add Queries:
	// The ending to: Add Init Data.

	return nil
}

// ClearDbData 清空数据库数据
func ClearDbData(db *gorm.DB) error {
	if db == nil {
		return errors.New("DBHandler: You Input a nil DB!")
	}
	// The beginning to: Clear Init Data:
	// Clear Companies:
	db.Delete(&CompaniesInitData)
	// Clear Jobs:
	db.Delete(&JobsInitData)
	// Clear Students:
	// Clear Discussions:
	// Clear Queries:
	// The ending to: Clear Init Data.
	return nil
}
